<template>
  <div class="app-container">
    <!-- 查询表单区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="收藏夹" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入收藏夹名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['collect:collections:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['collect:collections:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['collect:collections:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['collect:collections:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格展示区域 -->
    <el-table v-loading="loading" :data="collectionsList" @selection-change="handleSelectionChange" border stripe>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="收藏夹ID" align="center" prop="id" />
      <el-table-column label="所属用户ID" align="center" prop="userId" />
      <el-table-column label="收藏夹名称" align="center" prop="name" />
      <el-table-column label="封面图片" align="center">
        <template slot-scope="scope">
          <image-preview 
            :src="scope.row.coverImage" 
            :width="60" 
            :height="60" 
            v-if="scope.row.coverImage" 
          />
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <!-- 优化后的状态列，使用 Tag 标签区分状态 -->
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag 
            :type="scope.row.del === 0 ? 'success' : 'danger'"
            effect="light"
          >
            {{ scope.row.del === 0 ? '正常' : '已删除' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['collect:collections:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['collect:collections:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="收藏夹名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入收藏夹名称" />
        </el-form-item>
        <el-form-item label="封面图片" prop="coverImage">
          <image-upload v-model="form.coverImage" />
        </el-form-item>
        <el-form-item label="状态" prop="del">
          <el-radio-group v-model="form.del">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">已删除</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确认</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { 
  listCollections, 
  getCollections, 
  delCollections, 
  addCollections, 
  updateCollections
} from "@/api/collect/collections";
import ImageUpload from '@/components/ImageUpload';
import ImagePreview from '@/components/ImagePreview';
import Pagination from "@/components/Pagination";
import RightToolbar from "@/components/RightToolbar";

export default {
  name: "Collections",
  components: { ImageUpload, ImagePreview, Pagination, RightToolbar },
  data() {
    return {
      // 加载状态
      loading: true,
      
      // 选择器状态
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      
      // 数据列表
      total: 0,
      collectionsList: [],
      
      // 弹窗状态
      title: "",
      open: false,
      
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        name: null
      },
      
      // 表单数据
      form: {
        id: null,
        userId: null,
        name: null,
        coverImage: null,
        createTime: null,
        del: 0
      },
      
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: "收藏夹名称不能为空", trigger: "blur" }
        ],
        del: [
          { required: true, message: "请选择状态", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /**
     * 获取收藏夹列表
     */
    getList() {
      this.loading = true;
      listCollections(this.queryParams).then(response => {
        this.collectionsList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        console.error('获取收藏夹列表失败:', error);
        this.loading = false;
      });
    },
    
    /**
     * 取消操作
     */
    cancel() {
      this.open = false;
      this.reset();
    },
    
    /**
     * 重置表单
     */
    reset() {
      this.form = {
        id: null,
        userId: null,
        name: null,
        coverImage: null,
        createTime: null,
        del: 0
      };
      this.resetForm("form");
    },
    
    /**
     * 处理查询
     */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    
    /**
     * 重置查询
     */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    
    /**
     * 处理选择变化
     */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    
    /**
     * 新增按钮操作
     */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加收藏夹";
    },
    
    /**
     * 修改按钮操作
     */
    handleUpdate(row) {
      this.reset();
      const id = row ? row.id : this.ids;
      getCollections(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改收藏夹";
      }).catch(error => {
        console.error('获取收藏夹详情失败:', error);
      });
    },
    
    /**
     * 提交表单
     */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const action = this.form.id ? updateCollections : addCollections;
          action(this.form).then(() => {
            this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功");
            this.open = false;
            this.getList();
          }).catch(error => {
            this.$modal.msgError("操作失败：" + (error.message || "未知错误"));
          });
        }
      });
    },
    
    /**
     * 删除按钮操作
     */
    handleDelete(row) {
      const ids = row ? [row.id] : this.ids;
      this.$modal.confirm(`是否确认删除收藏夹编号为"${ids}"的数据?`).then(() => {
        return delCollections(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    
    /**
     * 导出按钮操作
     */
    handleExport() {
      this.download('collect/collections/export', { ...this.queryParams }, 
        `collections_${new Date().getTime()}.xlsx`);
    },
    
    /**
     * 重置表单字段
     */
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    }
  }
};
</script>

<style scoped>
/* 自定义样式 */
::v-deep .el-table {
  width: 100%;
}
::v-deep .el-table .fixed-width {
  width: 140px !important;
}
.small-padding ::v-deep .cell {
  padding: 5px 0 !important;
}
.dialog-footer {
  text-align: right;
}
/* 给状态 Tag 增加一点间距，避免太紧凑 */
::v-deep .el-table .el-tag {
  margin-right: 5px;
}
</style>